﻿using System.Web;
using DoNet.Helper;

namespace DoNet.Platform.TaoBao
{
    /// <summary>
    /// 淘宝网 Access Token
    /// </summary>
    public class TokenApi
    {
        /// <summary>
        /// 获取Access Token
        /// </summary>
        /// <param name="client_id">应用的API Key</param>
        /// <param name="client_secret">应用的Secret Key</param>
        /// <param name="code">用户授权后得到code </param>
        /// <param name="redirect_uri">参见redirect_uri的定义</param>
        /// <param name="state">应用发起请求时，所传的回调地址参数，在用户授权后应用会跳转至redirect_uri。</param>
        /// <param name="view">默认为web，view参数可选值有：web、tmall、wap，其中：Web对应普通的PC端（淘宝logo）浏览器页面样式。Tmall对应天猫的浏览器页面样式。Wap对应无线端的浏览器页面样式。</param>
        /// <returns></returns>
        public static ReturnData GetToken(string client_id, string client_secret, string code, string redirect_uri, string state = "", string view = "")
        {
            /*
            参数名字 参数选项 参数值 参数释义
            client_id 必选 appkey的值
            client_secret 必选 appsecret
            grant_type 必选 authorization_code
            code 必选 授权码
            redirect_uri 必选 参见redirect_uri的定义
            state 可选 维持应用的状态，传入值与返回值保持一致。
            view 可选  默认为web
            */
            Dictionary<string, string> props = new Dictionary<string, string>();
            props.Add("grant_type", "authorization_code");
            props.Add("code", code);
            props.Add("client_id", client_id);
            props.Add("client_secret", client_secret);
            props.Add("redirect_uri", HttpUtility.UrlEncode(redirect_uri));
            if (!string.IsNullOrWhiteSpace(state))
            {
                props.Add("state", state);
            }
            if (!string.IsNullOrWhiteSpace(view))
            {
                props.Add("view", view);
            }

            string param = JsonHelper.SerializeObject(props);
            string reqUrl = CommonConfig.WebApiUrl_WeiBo + "/oauth2/access_token";
            var result = HttpHelper.HttpPost(reqUrl, param);

            if (result.success)
            {
                var obj = JsonHelper.DeserializeObject<dynamic>(result.data);
                if (obj != null)
                {
                    /*
                    {  
                        "error_description": "request method must be post",
                        "error": "invalid_request"
                    }  
                    */
                    if (obj.error != null)
                    {
                        return new ReturnData()
                        {
                            success = false,
                            message = obj.error_description,
                            data = result.data
                        };
                    }
                    else
                    {
                        return result;
                    }
                }
                else
                {
                    return result;
                }
            }
            else
            {
                return result;
            }
        }

        /// <summary>
        /// 获取授权URL
        /// </summary>
        /// <param name="client_id">等同与appkey</param>
        /// <param name="redirect_uri">参见redirect_uri的定义</param>
        /// <param name="state">维持应用的状态，传入值与返回值保持一致。</param>
        /// <param name="view">默认为web</param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string client_id, string redirect_uri, string state = "", string view = "")
        {
            /*
            返回值说明   
            参数名字    参数选项    参数释义
            code    正常结果 授权码
            error   异常时返回   错误码
            error_description 异常时返回 错误描述 
            */
            string param = string.Format("?response_type=code&client_id={0}&redirect_uri={1}", client_id, HttpUtility.UrlEncode(redirect_uri));
            if(!string.IsNullOrWhiteSpace(state))
            {
                param += string.Format("&state={0}", state);
            }
            if (!string.IsNullOrWhiteSpace(view))
            {
                param += string.Format("&view={0}", view);
            }
            return CommonConfig.WebApiUrl_TaoBao_oauth + param;
        }
    }
}
